package com.unittec.drainage.provider.utils;

import java.util.ArrayList;
import java.util.List;

import com.unittec.drainage.provider.scope.ThreadLocalScope;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.common.base.Joiner;
import com.unittec.drainage.provider.ApplicationContextProvider;
import com.unittec.drainage.provider.log.Log;
import com.unittec.drainage.sdk.log.enums.LogOperateEnum;
import com.unittec.drainage.sdk.log.enums.LogStatusEnum;

/**
 * @author wuxinwei
 */
@Component
public class AsyncSendSms {

    @Autowired
    Log log;

    private static CommonResponse sendSmsAlibaba(String mobileString, JSONObject paramJson, String templateId,
        String accessKeyId, String accessKeySecret, String signName) {
        CommonResponse response = null;
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", mobileString);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateId);
        request.putQueryParameter("TemplateParam", paramJson.toJSONString());
        try {
            response = client.getCommonResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return response;
    }

    private static JSONObject sendMessage(ThreadLocalScope.AuthData authData, String mobileString, JSONObject paramJson,
                                          String templateId) {
        ThreadLocalScope.setAuthData(authData.getRequestId(), authData.getToken(), authData.getAppId(),
            authData.getTenantId(), authData.getIp(), authData.getUser(), authData.getAppCode(),
            authData.getUserName());
        long startLogTime = System.currentTimeMillis();
        JSONObject json = new JSONObject();
        Log log = ApplicationContextProvider.getApplicationContext().getBean(Log.class);

        Environment environment =
            (Environment)ApplicationContextProvider.getApplicationContext().getBean("environment");
        String signName = environment.getProperty("sms.signName");
        String accessKeyId = environment.getProperty("sms.accessKeyId");
        String accessKeySecret = environment.getProperty("sms.accessKeySecret");
        String smsSwitchStr = environment.getProperty("sms.smsSwitch");
        String whiteSwitchStr = environment.getProperty("sms.whiteSwitch");
        String whiteList = environment.getProperty("sms.whiteList");
        String blacklist = environment.getProperty("sms.blacklist");
        boolean smsSwitch = Boolean.parseBoolean(smsSwitchStr);
        boolean whiteSwitch = Boolean.parseBoolean(whiteSwitchStr);
        if (whiteSwitch) {
            mobileString = whiteList;
            log.addOperateLog("sendSMS", "发送白名单短信，白名单:" + whiteList, "发送短信", "发送短信成功", LogOperateEnum.LOG_ADD.getCode(),
                LogStatusEnum.SUCCESS.getCode(), startLogTime);
        }
        if (!smsSwitch) {
            json.put("code", "00000");
            String logSuccessContent = "发送短信成功,mobile:" + mobileString + ",param:" + paramJson.toJSONString();
            log.sysInfoLog("send SMS", logSuccessContent);
            log.addOperateLog("sendSMS", logSuccessContent, "发送短信", "发送短信成功", LogOperateEnum.LOG_ADD.getCode(),
                LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return json;
        }

        /**
         * 
         * 过滤黑名单
         */
        mobileString = filterBlackList(mobileString, blacklist);

        CommonResponse response =
            sendSmsAlibaba(mobileString, paramJson, templateId, accessKeyId, accessKeySecret, signName);
        boolean flag = false;
        if (response != null) {
            JSONObject jsonData = JSONObject.parseObject(response.getData());
            if ("OK".equals(jsonData.getString("Code"))) {
                json.put("code", "00000");
                json.put("message", jsonData.getString("Message"));
                flag = true;
            } else {
                json.put("code", "00001");
                json.put("message", jsonData.getString("Message"));
            }
        } else {
            json.put("code", "00001");
            json.put("message", "com.aliyuncs.CommonResponse java.lang.NullPointerException: null");
        }
        String logSuccessContent =
            "发送短信成功,mobile:" + mobileString + ",param:" + paramJson.toJSONString() + ",result:" + json.toJSONString();
        if (flag) {
            log.addOperateLog("sendSMS", logSuccessContent, "发送短信", "发送短信处理成功", LogOperateEnum.LOG_ADD.getCode(),
                LogStatusEnum.SUCCESS.getCode(), startLogTime);
        } else {
            log.addOperateLog("sendSMS", logSuccessContent, "发送短信", "发送短信处理失败", LogOperateEnum.LOG_ADD.getCode(),
                LogStatusEnum.ERROR.getCode(), startLogTime);
        }
        return json;
    }

    /**
     * 过滤黑名单
     *
     * @param mobileString
     * @param blacklist
     * @return
     */
    private static String filterBlackList(String mobileString, String blacklist) {
        if (StringUtils.isBlank(blacklist)) {
            return mobileString;
        }
        if (StringUtils.isBlank(mobileString)) {
            return "";
        }
        List<String> list = new ArrayList<>();
        for (String mobile : mobileString.split(",")) {
            boolean addFlag = true;
            for (String str : blacklist.split(",")) {
                if (mobile.equalsIgnoreCase(str)) {
                    addFlag = false;
                }
            }
            if (addFlag) {
                list.add(mobile);
            }
        }
        return Joiner.on(",").join(list);
    }

    @Async("taskExecutor")
    public void asyncSendSms(ThreadLocalScope.AuthData authData, String mobileString, JSONObject paramJson, String templateId) {
        try {
            sendMessage(authData, mobileString, paramJson, templateId);
        } catch (Exception e) {
            log.sysErrLog("asyncSendSms", e.getMessage(), e);
        }
    }

}
